package cn.seapon.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Scanner;
import java.util.logging.Logger;
import org.json.JSONObject;

public class HttpRequest {

	public static void main(String[] args) throws UnsupportedEncodingException{
		testLoadBalance2();
		testLoadBalance();
	}
	
	private static void testLoadBalance2() throws UnsupportedEncodingException {
		JSONObject object;
		String result ,location;
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		for(int i = 0;i < 100 ; i++){
			result = URLDecoder.decode(get("http://www.linzhv.com"),"utf-8");
			object = new JSONObject(result);
			location = object.getString("location");

			Integer integer = map.get(location);
			if(null == integer){
				map.put(location, 1);
			}else{
				map.replace(location, integer + 1);
			}
		}
		String info = "\n",key;
		Integer val;
		Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
		while(iterator.hasNext()){
			Map.Entry<String, Integer> entry = iterator.next();
			key = entry.getKey();
			val = entry.getValue();
			info += "HOST:"+key+"  TIMES:"+val+"\n";
		}
		Logger.getGlobal().info(info);
	}
	
	private static void testLoadBalance()  throws UnsupportedEncodingException {
		JSONObject object;
		String result ,location;
//		HashMap<String, Integer> map = new HashMap<>();
		int[] counts = {0,0,0,0};
		for(int i = 0;i < 100 ; i++){
			result = URLDecoder.decode(get("http://www.linzhv.com"),"utf-8");
			object = new JSONObject(result);
			location = object.getString("location");
//			Map.Entry<String, Integer> enrty = map.get(key)
			switch (location) {
				case "c7n17:8081":
					counts[0] ++;
					break;
				case "c7n17:8082":
					counts[1] ++;
					break;
				case "c7n17:8083":
					counts[2] ++;
					break;
				case "c7n17:8084":
					counts[3] ++;
					break;
			}
		}
		int i = 4;
		String info = "\n";
		while(i-- != 0){
			info += "host(808"+(i+1)+"):"+counts[i]+"\n";
		}
		Logger.getGlobal().info(info);
	}

	
	
	/**
	 * do get request
	 * @param string urlString request url  如果带有请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 * @return string|null
	 */
	public static String get(String urlString) {
		OutputStream out = null;
		InputStream in = null;
		try {
			URL url = new URL(urlString);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			con.setRequestMethod("GET");    
			//设置输入输出权限
			con.setDoInput(true);
			con.setDoOutput(true);
			//禁用缓存
			con.setUseCaches(false);
			//设置请求头
			con.setRequestProperty("Charset", "UTF-8");
			con.setRequestProperty("accept", "*/*");
			con.setRequestProperty("connection", "Keep-Alive");
			con.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");//兼容IE6
			
			in = con.getInputStream();
			BufferedReader bfr = new BufferedReader(new InputStreamReader(in));
			String line = bfr.readLine();

//			System.out.println("输入的URL地址是："+urlString+"\n\tSAE返回的json字符串是："+line);
			return line;
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}finally{
			try {
				if (out != null) out.close();
				if (in != null) in.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
	}
	
	public static String post(String urlString,String param) throws IOException {
		URL url = new URL(urlString);
		URLConnection connection = url.openConnection();
		connection.setDoInput(true);
		connection.setDoOutput(true);
        // 设置通用的请求属性
		connection.setRequestProperty("accept", "*/*");
        connection.setRequestProperty("connection", "Keep-Alive");
        connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
		PrintWriter pw = new PrintWriter(connection.getOutputStream());
		pw.print(param);
		pw.close();
		StringBuilder response = new StringBuilder();
		Scanner scanner = null;
		try {
			scanner = new Scanner(connection.getInputStream());
			while (scanner.hasNextLine()) {
				response.append(scanner.nextLine());
			}
		} catch (IOException e) {
			InputStream errStream = ((HttpURLConnection) connection).getErrorStream();
			if (errStream == null) {
				throw e;
			}
			scanner = new Scanner(errStream);
			while (scanner.hasNextLine()) {
				response.append(scanner.nextLine()+"\n");
			}
		}finally {
			if(scanner != null) scanner.close();;
		}
		System.out.println(response.toString());
		return response.toString();
	}
	
	public static String post(String urlString,Map<String, String> nameValuePair) throws IOException{
		StringBuilder builder = new StringBuilder();
		boolean isFirst = true;
		for (Map.Entry<String, String> pair : nameValuePair.entrySet() ) {
			if (isFirst) {
				isFirst = false;
			}else {
				builder.append("&");
			}
			builder.append(pair.getKey());
			builder.append("=");
			builder.append( URLEncoder.encode(pair.getValue(), "UTF-8") );
		}
		return post(urlString, builder.toString());
	}
	
}
